using System.Linq;
using System.Text.RegularExpressions;
using BusinessLogic.Managers.Processing.ProcessingExceptions;
using BusinessLogic.Managers.Processing.RemittanceAdvice.Exceptions;
using BusinessLogic.Mappers;
using DataAccess.Services;

namespace BusinessLogic.Managers.Processing.RemittanceAdvice.ValidationRules
{
	internal class RemittanceAdviceNumberValidationRule : IRemittanceAdviceValidationRule
	{
		public void Validate(BusinessEntity.Entities.RemittanceAdvice remittanceAdvice, IServiceManager serviceManager)
		{
			string number = remittanceAdvice.Number;

			CheckLength(number);
			CheckFormat(number);
			CheckDuplication(remittanceAdvice.PayerPartyAccount.ID, number, serviceManager);
		}

		private static void CheckDuplication(int payerAccountPartyId, string number, IServiceManager serviceManager)
		{
			if (MapperFactory.GetRemittanceAdviceMapper(serviceManager).GetExistingRemittanceAdviceNumbersForClientByAccountCode(payerAccountPartyId).Contains(number))
			{
				throw new DuplicateDocumentNumberException(number);
			}
		}

		private static void CheckLength(string number)
		{
			if (number.Length < 8 || number.Length > 25)
			{
				throw new InvalidRemittanceAdviceNumberLengthException(number);
			}
		}

		private static void CheckFormat(string number)
		{
			var regex = new Regex("^[A-Za-z0-9]+$");

			if (!regex.IsMatch(number))
			{
				throw new InvalidRemittanceAdviceNumberFormatException(number);
			}
		}
	}
}